package com.wzh.product.mq;

import com.rabbitmq.client.Channel;
import com.wzh.product.dao.MydisDao;
import com.wzh.product.entity.MydisEntity;
import com.wzh.product.util.MsgUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author WZH
 * @title: Consumer
 * @projectName t1_1.22
 * @description:
 * @date 2022/1/22
 */
@Component
public class Consumer {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MydisDao mydisDao;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @RabbitListener(queues = "msg")
    public void take01(String tel, Message message, Channel channel) throws IOException {
        int code = new Random().nextInt(89999)+10000;
        MsgUtil.sendMsg(tel,code+"");
        System.out.println("mq发送验证码"+new Date().toLocaleString());
        redisTemplate.boundValueOps(tel).set(code);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @RabbitListener(queues = "msg2")
    public void take02(MydisEntity mydisEntity,Message message,Channel channel) throws IOException {
        //优惠券系统消费者在接收到消息之后，使用线程池发送优惠券（2分）
        threadPoolExecutor.submit(()->{
            int insert = mydisDao.insert(mydisEntity);
            System.out.println(insert);
        });
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
